
(function($) {
    jQuery.fn.calendar = function(options) {
        var defualts = {choose:"single",behavior: "click",mode:"day",setmode:["day","week","month"],limit:0,daylist:3,monthlist:3,weeklist:3,modechange:false }/*choose:"multiple"   choose:"single"   */
            ,calendarOpn = $.extend({}, defualts, options)
            /*,wDays = ['周日','周一','周二','周三','周四','周五','周六']*/
            ,daySecond = 1000 * 60 * 60 * 24
            ,Today = new Date()
			,nYear = Today.getFullYear()
			,nMonth = Today.getMonth()
			,defaultMode = ["day","week","month"]	
			,inputStr = (calendarOpn.input).replace(/\./g,"")		
            ,CalendarBox = '<div id="CalendarBox" class="CalendarBox_'+ inputStr +'" iclass="'+ calendarOpn.input +'" timetype="'+ calendarOpn.choose +","+ calendarOpn.mode +'"><div class="calendarTab"><div class="dwm"><span class="day cur">日</span><span class="week">周</span><span class="month">月</span></div></div><div class="calendarNav"><span id="prevNav" title="上">上</span><span id="nextNav" title="下">下</span><span id="cSltNav"></span></div></div>';
        $(this).bind(calendarOpn.behavior,function(){
			var left = $("input"+ calendarOpn.input +":first").offset().left-310
				,top = $("input"+ calendarOpn.input +":first").offset().top+19;
            closeCalendar();
            $(CalendarBox).appendTo($("body")).css({top:top+"px",left:left+"px"});
            if(calendarOpn.setmode.length < 3){
                for(var aA = 0;aA <3;aA++){
                    var NsMode = defaultMode[aA];
                    if(jQuery.inArray(NsMode,calendarOpn.setmode) == -1){
						    $(".calendarTab").remove();
						$("#CalendarBox").css("padding-top","0px");
						$("#CalendarBox").css("width","165px")
						$("#CalendarBox").css("margin-right","28px")
                    }
                }
            }
            $(".calendarTab>.dwm>span."+calendarOpn.mode,"#CalendarBox").addClass("cur").siblings("span").removeClass("cur");
            if(calendarOpn.modechange){
                calendarOpn.choose = "multiple";
                modeChange();
				}else{
                calenderMode(calendarOpn.mode,1);
            }
            if(calendarOpn.choose == "multiple"){
                $('<b class="cancelCalendar reset ml5 mr10">取消</b><b class="configCalendar confirm">确定</b>').appendTo($("#CalendarBox > .calendarTab"));
            }
            return false;
        });
        /**
         * 日历模式切换
        */
        function modeChange(){
            $(".calendarTab>.dwm>span","#CalendarBox").hover(function(){
                var thisClass = $(this).attr("class")
                    ,thisMode = thisClass.replace(/[cur]|\s/g,"")
					,selectType = $("input"+ calendarOpn.input).attr("timetype");
                $(this).addClass("cur").siblings("span").removeClass("cur");
                $(".CalendarBox","#CalendarBox").remove();
                $("#CalendarBox").attr("timetype","multiple,"+thisMode);
				 if(selectType){
                    var setMode = typeJudge(selectType,thisMode)?1:0;
                }
                calenderMode(thisMode,setMode);
                $("#cSltNav").text("");
                return false;
            });
            var timeType = $("input"+calendarOpn.input).attr("timetype");
            if(timeType){
                timeType = timeType.split(",");
                $(".calendarTab>.dwm>span."+timeType[1],"#CalendarBox").trigger("mouseover");
            }else{
                $(".calendarTab>.dwm>span","#CalendarBox").eq(0).trigger("mouseover");
            }
            return false;
        }

        /**
         * 日历模式
         * @param Mode 传入日历模式
   * @param Mode 传入当前日历模式
         */
        function calenderMode(Mode,nowMode){
             var getYear = nYear
                ,getMonth = nMonth+1
                ,haveSelect = 0
                ,listDateLen = calendarOpn.daylist
                ,endTime,startTime,startArr;
            if(nowMode){
                endTime = $("input"+ calendarOpn.input +":last").val();
                if(endTime){
                    startArr = endTime.split(/-|\./g);
                    if(endTime&&(/^(1|2\d{3}-|.)/).test(endTime)){
                        startTime = $("input"+ calendarOpn.input +":first").val();
                        getYear = startArr[0];
                        getMonth = startArr[1];
                        haveSelect = 1;
                    }
                }else if(!endTime&&calendarOpn.limit){
                    startArr = (calendarOpn.limit).split(/-|\./g);
                    getYear = startArr[0];
                    getMonth = startArr[1];
                }
            }
            if(Mode == "day" || !Mode){
                var m = Number(getMonth)
                    ,y = getYear
                    ,z=0;
                for(var i = listDateLen-1;i>=0;i--){
                    if(m-z == 0){
                        z = 0;
                        m = 12;
                        y = Number(getYear)-1;
                    }
                    if(i==listDateLen-1){
                        monthFun(y,m-z);
                    }else{
                        monthFun(y,m-z,1);
                    }
                    z++;
                }
            }else if(Mode == "week"){
                var startYear = Number(getYear)
                    ,listDateLen = calendarOpn.weeklist;
                for(var i = 0;i<listDateLen;i++){
                       if( i==0){
                        weekFun(startYear-i);
                    }else{
                        weekFun(startYear-i,1);
                    }
                }
            }else if(Mode == "month"){
                $('<table cellspacing="0" cellpadding="0" border="0" class="CalendarBox calendarMonth"></table>').appendTo($("#CalendarBox"));
                var startYear = Number(getYear)
                    ,listDateLen = calendarOpn.monthlist;
                for(var i = listDateLen-1;i>=0;i--){
					yearFun(startYear-i);
                } 
            }
            if(haveSelect){
                haveSelectTime(startTime,endTime);
            }else{
                $("td.dateSelect","#CalendarBox").removeClass("dateSelect");
            }
            prevNext();
            TimeHover();
            TimeSelect();
            calenderClose();
        } 


        /**
         * 默认选择时间
         * @param startTime 已选择开始时间
         * @param endTime 已选择结束时间
         */
        function haveSelectTime(startTime,endTime){
            $("td.csTime[title*="+ startTime  +"]","#CalendarBox").addClass("dateSelect");
            $("td.csTime[title*="+ endTime  +"]","#CalendarBox").addClass("dateSelect");
            if(calendarOpn.choose = "multiple"){
                var $Td = $("td.csTime","#CalendarBox")
                    ,sSelectIndex = $Td.index($("td.dateSelect:first","#CalendarBox"))
                    ,eSelectIndex = $Td.index($("td.dateSelect:last","#CalendarBox"));
                $Td.each(function(n){
                    if(n > sSelectIndex && n < eSelectIndex){
                        $(this).addClass("dateSelect");
                    }
                });
            }
        }
        /**
         * 周-日历生成
         * @param yearFn 年
         * @param Prepend 是否插入前端
         */
        function weekFun(yearFn,Prepend){
            var yearFirstNewDate = new Date(yearFn+"/01/01")
                ,yearFirstDay = yearFirstNewDate.getDay()
                ,yearLastDay = (new Date(yearFn+"/12/31")).getDay()
                ,yearFirstParse = Date.parse(yearFirstNewDate)
                ,yearBaginParse = yearFirstParse
                ,weekStr = "";
            if(yearFirstDay > 0 && yearFirstDay <= 4){
                yearBaginParse -= yearFirstDay*daySecond;
            }else if(yearFirstDay > 4){
                yearBaginParse += (7-yearFirstDay)*daySecond;
            }
            for(var Wi = 1;Wi <= 54 ;Wi++){
                var thisDateParse = yearBaginParse+Wi*7*daySecond
                    ,weekBaginParse = thisDateParse-6*daySecond
                    ,WeekBagin = new Date(weekBaginParse)
                    ,WeekLast = new Date(thisDateParse);
                if(WeekBagin.getFullYear()==yearFn||WeekLast.getFullYear()==yearFn){
                    if(limitTime()){
                        if(weekBaginParse <= limitTime()){
                            weekStr+='<td class="csTime" title="'+ WeekBagin.getFullYear()+'-'+numDeal((Number(WeekBagin.getMonth())+1))+'-'+numDeal(WeekBagin.getDate())+' 至 '+ WeekLast.getFullYear()+'-'+numDeal((Number(WeekLast.getMonth())+1))+'-'+numDeal(WeekLast.getDate()) +'">'+ Wi +'</td>';
                        }else{
                            weekStr+='<td class="ncsTime">'+ Wi +'</td>';
                        }
                    }else{
                        if(WeekLast.getFullYear() > yearFn  && Number(WeekLast.getDate()) > 3){
                           weekStr+='<td></td>';
                        }else{
                            weekStr+='<td class="csTime" title="'+ WeekBagin.getFullYear()+'-'+numDeal((Number(WeekBagin.getMonth())+1))+'-'+numDeal(WeekBagin.getDate())+' 至 '+ WeekLast.getFullYear()+'-'+numDeal((Number(WeekLast.getMonth())+1))+'-'+numDeal(WeekLast.getDate()) +'">'+ Wi +'</td>';
                        }
                    }
                }else{
                    weekStr+='<td></td>';
                }
                if(Wi%18 == 0 && Wi<54){
                    weekStr+="</tr><tr>";
                }else if(Wi%18 == 0 && Wi==54){
                    weekStr+="</tr>";
                }
            }
            weekStr = "<tr><th rowspan='3'>"+ yearFn +"</th>" + weekStr;
            if(!Prepend){
                $('<table cellspacing="0" cellpadding="0" border="0" class="CalendarBox calendarWeek">'+ weekStr +'</table>').appendTo($("#CalendarBox"));
            }else{
                $('<table cellspacing="0" cellpadding="0" border="0" class="CalendarBox calendarWeek">'+ weekStr +'</table>').insertBefore($("#CalendarBox>table.calendarWeek:first"));
            }
        }
        /**
         * 月-日历生成
         * @param yearFn 年
         * @param Prepend 是否插入前端
         */
               function yearFun(yearFn,Prepend){
            var monthTd = "";
            for(var Mi=0;Mi<13;Mi++){
                if(Mi==0){
                    monthTd =monthTd+"<th>"+ yearFn +"</th>";
                }else{
                    var monthStrFirst = yearFn+"-"+numDeal(Mi)+"-01"
                        ,monthSrtFirstParse = Date.parse(yearFn+"/"+numDeal(Mi)+"/01")
                        ,monthStrLast = yearFn+"-"+numDeal(Mi)+"-"+ymDays(yearFn,Mi-1)
                    if(limitTime()){
                        if(monthSrtFirstParse < limitTime()){
                            monthTd = monthTd+'<td class="csTime" title="'+monthStrFirst+" 至 "+ monthStrLast +'">'+ Mi +'</td>';
                        }else{
                            monthTd =monthTd+'<td class="ncsTime">'+ Mi +'</td>';
                        }
                    }else{
                        monthTd = monthTd+'<td class="csTime" title="'+monthStrFirst+" 至 "+ monthStrLast +'">'+ Mi +'</td>';
                    }

                }
            }

            monthTd = "<tr>"+ monthTd +"</tr>"
            if(!Prepend){
                $(monthTd).appendTo($("#CalendarBox>table"));
            }else{
                $(monthTd).prependTo($("#CalendarBox>table"));
            }
        }
        /**
         * 日-日历生成
         * @param yearFun 年
         * @param monthFun 月
         * @param Prepend 是否插入前端
         */
        function monthFun(yearFun,monthFun,Prepend){
            var DayTable = "<div class='CalendarBox calenderday' datemonth="+yearFun+"/"+monthFun +"><b>"+yearFun+"年"+numDeal(monthFun) +"月</b><table><tr><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th><th>日</th></tr></table></div>";
            if(!Prepend){
                var thisMonthDayTable = $(DayTable).appendTo($("#CalendarBox"));
            }else{
                var thisMonthDayTable = $(DayTable).insertBefore($("#CalendarBox>.CalendarBox:first"));
            }
            var dayTr = "<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
            var monthFirst = new Date(yearFun+"/"+monthFun+"/01"),
                monthFirstDateDay = monthFirst.getDay();
            if( monthFirstDateDay> 0 && monthFirstDateDay <= 6){
                var monthFirstDay = monthFirst.getDay() -1;
            }else if(monthFirstDateDay == 0){
                var monthFirstDay = 6;
            }
            var  monthParseBagin = Date.parse(yearFun+"/"+monthFun+"/1") - monthFirstDay*daySecond;
            $(dayTr).appendTo($("table",thisMonthDayTable));
           for(var Di = 0;Di < ymDays(yearFun,monthFun-1) + monthFirstDay;Di++){
                var nowParse = monthParseBagin+Di*daySecond
                    ,getMonthDayParse = new Date(nowParse);
                $("td",thisMonthDayTable).eq(Di).attr({title:(getMonthDayParse.getFullYear()+"-"+numDeal(getMonthDayParse.getMonth()+1)+"-"+numDeal(getMonthDayParse.getDate()))}).text(getMonthDayParse.getDate());
                if(Di > monthFirstDay-1){
                    if(limitTime() && nowParse > limitTime()){
                        $("td",thisMonthDayTable).eq(Di).addClass("ncsTime");
                    }else{
                        $("td",thisMonthDayTable).eq(Di).addClass("csTime");
                    }
                }
                if((Di+1)%7 == 0 && Di < (ymDays(yearFun,monthFun-1) + monthFirstDay)-1 ){  $(dayTr).appendTo($("table",thisMonthDayTable)); }
            }
            return false;
        }
        /**
         * 限选日期
         * @return {Date}
         */
        function limitTime(){
            var limit = calendarOpn.limit;
            if(limit){
                return Date.parse(limit.replace(/-/g,"/"));
            }else{
                return false;
            }
        }

        /**
         * 向前或向后选择
         */
        function prevNext(){
            /**
             * 向前
             */
            $("#CalendarBox>.calendarNav>#prevNav").live("click",function(){
                var CalendarType = $("#CalendarBox").attr("timetype");
                if(typeJudge(CalendarType,"day")){
                    var getTableMonthData = $("#CalendarBox>.CalendarBox:eq(0)").attr("datemonth"),
                        thisMonth = getTableMonthData.split("/");
                    if(thisMonth[1]==1){
                        monthFun(Number(thisMonth[0])-1,12,1);
                    }else{
                        monthFun(thisMonth[0],Number(thisMonth[1])-1,1);
                    }
                    $("#CalendarBox>.CalendarBox:last").remove();
                }else if(typeJudge(CalendarType,"month")){
                    var thisMonthYear = Number($("th:first","#CalendarBox").text());
                    $("tr:last","#CalendarBox").remove();
                    yearFun(thisMonthYear-1,1);
                }else if(typeJudge(CalendarType,"week")){
                    var thisMonthYear = Number($("th:first","#CalendarBox").text());
                    $(".calendarWeek:last","#CalendarBox").remove();
                    weekFun(thisMonthYear-1,1);
                }
                return false;
            });
            /**
             * 向后
             */
            $("#CalendarBox>.calendarNav>#nextNav").live("click",function(){
                var CalendarType = $("#CalendarBox").attr("timetype");
                if(typeJudge(CalendarType,"day")){
                    var getTableMonthData = $("#CalendarBox>.CalendarBox:last").attr("datemonth"),
                        thisMonth = getTableMonthData.split("/");
                    if(thisMonth[1]==12){
                        monthFun(Number(thisMonth[0])+1,1);
                    }else{
                        monthFun(thisMonth[0],Number(thisMonth[1])+1);
                    }
                    $("#CalendarBox>.CalendarBox:first").remove();
                }else if(typeJudge(CalendarType,"month")){
                    var thisMonthYear =  Number($("th:last","#CalendarBox").text());
                    $("tr:first","#CalendarBox").remove();
                    yearFun(thisMonthYear+1);
                }else if(typeJudge(CalendarType,"week")){
                    var thisMonthYear =  Number($("th:last","#CalendarBox").text());
                    $(".calendarWeek:first","#CalendarBox").remove();
                    weekFun(thisMonthYear+1);
                }
                return false;
            });
        }
        /**
         * 时间单击选择
         * @constructor
         */
        function TimeSelect(){
            $("td.csTime","#CalendarBox").live("click",function(){
                var timeType = $("#CalendarBox").attr("timetype")
                    ,inputClass = $("#CalendarBox").attr("iclass");
                if(typeJudge(timeType,"single")){
                    if(typeJudge(timeType,"day")){
                        var Daytime = charDeal($(this).attr("title"));
                        $("input"+inputClass).val(Daytime);
                    }else if(typeJudge(timeType,"month")||typeJudge(timeType,"week")){
                        var thisMonthTime = ($(this).attr("title")).split("至");
                        $("input"+inputClass+":first").val(charDeal(thisMonthTime[0]));
                        $("input"+inputClass+":last").val(charDeal(thisMonthTime[1]));
                    }
                    closeCalendar();
                }else if(typeJudge(timeType,"multiple")){
                    var selectTimeNum = $(".dateSelect","#CalendarBox").length
                        ,TdcsTime = $("td.csTime","#CalendarBox")
                        ,thisTimeTxt = $(this).attr("title");
                    if(selectTimeNum==0){
                        $(this).addClass("dateSelect");
                    }else if(selectTimeNum==1){
                        var thisSelectIndex = TdcsTime.index(this)
                            ,hasSelectIndex = TdcsTime.index($("td.dateSelect","#CalendarBox"))
                            ,selectArr = Sort([thisSelectIndex,hasSelectIndex])
                            ,selectStart;
                        TdcsTime.each(function(n){
                            if(n >= selectArr[0] && n <= selectArr[1]){
                                $(this).addClass("dateSelect");
                            }
                        });
                        if(typeJudge(timeType,"day")){
                            selectStart = charDeal($("td.dateSelect:first","#CalendarBox").attr("title"));
                            thisTimeTxt = selectStart+" 至 "+charDeal($("td.dateSelect:last","#CalendarBox").attr("title"));
                        }else{
                            selectStart = charDeal((($("td.dateSelect:first","#CalendarBox").attr("title")).split("至"))[0]);
                            thisTimeTxt =  selectStart+" 至 "+charDeal(($("td.dateSelect:last","#CalendarBox").attr("title").split("至"))[1]);
                        }
                    }else if(selectTimeNum>1){
                        TdcsTime.removeClass("dateSelect");
                        $(this).addClass("dateSelect");
                    }
                    $("#cSltNav").text(thisTimeTxt);
                    selectTimeOk();
                    cancelSelectCalendar();
                }
                return false;
            });
        }

        /**
         * 确定选择日期
         */
        function selectTimeOk(){
            $(".configCalendar","#CalendarBox").live("click",function(){
                var inputClass = $("#CalendarBox").attr("iclass")
                    ,timetype = $("#CalendarBox").attr("timetype");
                if(typeJudge(timetype,"day")){
                    var DaytimeFirst = charDeal($(".dateSelect:first","#CalendarBox").attr("title"))
                        ,DaytimeLast = charDeal($(".dateSelect:last","#CalendarBox").attr("title"));
                }else if(typeJudge(timetype,"month")||typeJudge(timetype,"week")){
                    var DaytimeFirst = charDeal((($(".dateSelect:first","#CalendarBox").attr("title")).split("至"))[0])
                        ,DaytimeLast = charDeal((($(".dateSelect:last","#CalendarBox").attr("title")).split("至"))[1]);
                }
                $("input"+inputClass+":first").val(DaytimeFirst);
                $("input"+inputClass+":last").val(DaytimeLast);
                $("input"+inputClass).attr("timetype",timetype);
                closeCalendar();
				doAction();
                return false;
            });
        }

        /**
         * 取消选择日期
         */
        function cancelSelectCalendar(){
           $(".cancelCalendar").live("click",function(){
              $("td.dateSelect","#CalendarBox").removeClass("dateSelect");
              $("#cSltNav").text("");
           });
        }
        /**
         * 日期鼠标经过效果
         * @constructor
         */
        function TimeHover(){
            $("td.csTime","#CalendarBox").live("mouseover",function(){
                $(this).addClass("dateHover");
            }).live("mouseout",function(){
                $(this).removeClass("dateHover");
            });
        }
        /**
         * 根据年月求某月天数
         * @param yearNum 年
         * @param monthNum 月
         * @return {Array} 某月有几天
         */
        function ymDays(yearNum,monthNum){
            var monthArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            if (((yearNum % 4 == 0) && (yearNum % 100 != 0)) || (yearNum % 400 == 0))monthArray[1] = 29;
            return monthArray[monthNum];
        }

        /**
         * 数组数据排序
         * @param sortArray 数组
         * @return {*} 由小到大排序数组
         * @constructor
         */
        function Sort(sortArray){
            return sortArray.sort(function(a,b){return a>b?1:-1});
        }

        /**
         * 关闭日历
         */
        function calenderClose(){
            $("#CalendarBox").siblings().click(function(){
                closeCalendar();
            });
        }

        /**
         * 关闭日历
         */
        function closeCalendar(){
            $("#CalendarBox").remove();
        }
        /**
         * 数字处理
         * @param num 数字
         * @return {String}返回两位数字
         */
        function numDeal(num){
            return num < 10 ? "0" + num : num;
        }

        /**
         * 去空格及汉字
         * @param str 带有汉字或空格的字符串
         * @return {*}返回数字字符串
         */
        function charDeal(str){
            return str.replace(/\s|[\u4e00-\u9fa5]/g,"");
        }

        /**
         * 判断是否含有某字符
         * @param Judgetype 判断的字符串
         * @param type 含有的字符串
         * @return {Boolean}
         */
        function typeJudge(Judgetype,type){
            if(Judgetype.indexOf(type)> -1){
                return true;
            }else{
                return false;
            }
        }
        return false;
    };
})(jQuery);
$(function(){
	eventApi();
});
/**
*日历事件接口
*/
function eventApi(){
	$(".csTime",".CalendarBox_date2").live("click",function(){				
		setTimeout(function(){
			alert($(".date2").val());
			
		},1000);
	});
	$(".csTime",".CalendarBox_date3").live("click",function(){				
		setTimeout(function(){
			alert($(".date3").val());
			
		},1000);
	});
}